package com.dhcc.bpm.modules.system.controller;

import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.exception.BusinessException;
import com.dhcc.bpm.common.utils.ExcelUtil;
import com.dhcc.bpm.modules.common.entity.Upload;
import com.dhcc.bpm.modules.common.service.IPluploadService;
import com.dhcc.bpm.modules.cost.controller.CostRuleController;
import com.dhcc.bpm.modules.system.entity.Dict;
import com.dhcc.bpm.modules.system.service.IDictService;
import com.dhcc.bpm.modules.system.vo.DictQueryVo;
import com.dhcc.bpm.modules.system.vo.DictVO;
import com.dhcc.bpm.modules.system.wrapper.DictWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.node.INode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.springblade.core.cache.constant.CacheConstant.SYS_CACHE;
/**
 * @ClassName DictController
 * @Description 控制器
 * @Author sjm
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/dict")
@Api(value = "字典", tags = "字典")
public class DictController extends BladeController {
	private static final Logger log = LoggerFactory.getLogger(CostRuleController.class);
    @Autowired
    private IPluploadService pluploadService;
	private IDictService dictService;
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	/**
	 * @Description 详情
	 * @Author sjm
	 * @Date 10:02 2020/2/22 0022
	 * @param dict
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.system.vo.DictVO>
	 **/
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入dict")
	@ApiLog("字典详情")
	@Log(title = "字典详情", businessType = BusinessType.SELECT)
	public R<DictVO> detail(Dict dict) {
		Dict detail = dictService.getOne(Condition.getQueryWrapper(dict));
		return R.data(DictWrapper.build().entityVO(detail));
	}

	/**
	 * @Description 列表
	 * @Author sjm
	 * @Date 10:02 2020/2/22 0022
	 * @param dict
	 * @return org.springblade.core.tool.api.R<java.util.List<org.springblade.core.tool.node.INode>>
	 **/
	@RequestMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "字典编号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "dictValue", value = "字典名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入dict")
	@ApiLog("字典列表")
	@Log(title = "字典列表", businessType = BusinessType.SELECT)
	public R<List<INode>> list(@ApiIgnore @RequestParam Map<String, Object> dict) {
		List<Dict> list = dictService.selectDictList(Condition.getQueryWrapper(dict, Dict.class).lambda().orderByAsc(Dict::getSort));
		return R.data(DictWrapper.build().listNodeVO(list));
	}

	/**
	 * @Description 获取字典树形结构
	 * @Author sjm
	 * @Date 10:02 2020/2/22 0022
	 * @param
	 * @return org.springblade.core.tool.api.R<java.util.List<com.dhcc.bpm.modules.system.vo.DictVO>>
	 **/
	@GetMapping("/tree")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "树形结构", notes = "树形结构")
	@ApiLog("获取字典树形结构")
	@Log(title = "获取字典树形结构", businessType = BusinessType.SELECT)
	public R<List<DictVO>> tree() {
		List<DictVO> tree = dictService.tree();
		return R.data(tree);
	}

	/**
	 * @Description 新增或修改
	 * @Author sjm
	 * @Date 10:03 2020/2/22 0022
	 * @param dict
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增或修改", notes = "传入dict")
	@ApiLog("新增或修改字典")
	@Log(title = "字典", businessType = BusinessType.INSERT)
	public R submit(@Valid @RequestBody Dict dict) {
		dict.setExpSeq(stringRedisTemplate.opsForValue().get("expSeq"));
		return R.status(dictService.submit(dict));
	}


	/**
	 * @Description 删除
	 * @Author sjm
	 * @Date 10:03 2020/2/22 0022
	 * @param ids
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/remove")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "删除", notes = "传入ids")
	@CacheEvict(cacheNames = {SYS_CACHE}, allEntries = true)
	@ApiLog("删除字典")
	@Log(title = "字典", businessType = BusinessType.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(dictService.removeDict(ids));
	}

	/**
	 * @Description 获取字典
	 * @Author sjm
	 * @Date 10:03 2020/2/22 0022
	 * @param code
	 * @return org.springblade.core.tool.api.R<java.util.List<com.dhcc.bpm.modules.system.entity.Dict>>
	 **/
	@GetMapping("/dictionary")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取字典", notes = "获取字典")
	@ApiLog("获取字典")
	@Log(title = "获取字典", businessType = BusinessType.SELECT)
	public R<List<Dict>> dictionary(String code) {
		List<Dict> tree = dictService.getList(code);
		return R.data(tree);
	}

	/**
	 * @Description 根据Key获取字典
	 * @Author sjm
	 * @Date 10:03 2020/2/22 0022
	 * @param dict
	 * @return java.util.List<com.dhcc.bpm.modules.system.vo.DictQueryVo>
	 **/
	@PostMapping("/getDict")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "根据Key获取字典", notes = "传入名称")
	@ApiLog("根据Key获取字典")
	@Log(title = "根据Key获取字典", businessType = BusinessType.SELECT)
	public List<DictQueryVo> getDictByKey( @RequestBody DictVO dict){
		List<DictQueryVo> list = new ArrayList<>();
		if(dict==null || StringUtils.isBlank(dict.getCode())){
		    return null;
        }
		List<Dict> tree = dictService.getList(dict.getCode());
		log.info("name:{}---tree{}", dict.getCode(), tree);
		for (Dict i : tree){
			DictQueryVo dictQueryVo = new DictQueryVo();
			dictQueryVo.setItem_name(i.getDictValue());
			dictQueryVo.setItem_no(i.getDictKey());
			dictQueryVo.setColor(i.getDictColor());
			list.add(dictQueryVo);
		}
		return list;
	}
    /**
     * @Description 元数据导入
     * @Author wjh
     * @Date 2020年8月17日14:08:30
     * @param request
     **/
    @PostMapping("/import")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入dict")
    @ApiLog("文件导入")
    @Log(title = "文件导入", businessType = BusinessType.IMPORT)
    public R<Boolean> excelToDict(HttpServletRequest request) throws Exception{
        Upload upload = new Upload();
        upload.setRequest(request);
        Upload uploadEntity = pluploadService.getFile(upload);
        MultipartFile multipartFile = uploadEntity.getMultipartFile();
        ExcelUtil<Dict> util = new ExcelUtil<Dict>(Dict.class);
        List<Dict> dictLists = util.importExcel(multipartFile.getInputStream());
        Boolean flag = true;
        if(dictLists != null && dictLists.size() != 0){
            for (Dict metadata:dictLists){
                flag =dictService.save(metadata);
            }
        }else{
            flag = false;
            throw new BusinessException("导入数据不能为空！");
        }
        return R.data(flag);
    }
}
